package com.csj.mvvmtest.ui.first

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.csj.mvvm.bean.NotifyEntity
import com.csj.mvvm.ui.base.BaseFragment
import com.csj.mvvm.ui.base.StartAct.onStart
import com.csj.mvvm.utils.LogUtil
import com.csj.mvvm.utils.ToastUtil
import com.csj.mvvmtest.bean.ArticleBean
import com.csj.mvvmtest.databinding.FragmentFirstBinding
import com.csj.mvvmtest.notification.NotificationMr
import com.csj.mvvmtest.ui.MainActivity
import com.csj.mvvmtest.ui.demo.SSDemoActivity
import com.csj.mvvmtest.ui.first.adapter.ArticleListAdapter
import com.csj.mvvmtest.util.DeviceIdUtil

class FirstFragment : BaseFragment<MainViewModel, FragmentFirstBinding>() {
    private lateinit var adapter: ArticleListAdapter
    private var list = ArrayList<ArticleBean>()
    private var page: Int = 0
    private var total: Int = 30//每页请求的数量
    private var canLoad = true

    private var isLogin = false

    override fun initClick() {

    }

    override fun initData() {
        adapter = ArticleListAdapter(mContext, list)
        adapter.itemClick { view, pos ->
            when (pos) {
//                0 -> ImageActivity.start(
//                    mContext,
//                    view,
//                    "http://5b0988e595225.cdn.sohucs.com/q_70,c_zoom,w_640/images/20200218/f0cab2beb92d4c70a4fe1b25ac322bfb.jpeg"
//                )
                0 -> {
                    val uuid = DeviceIdUtil.getDeviceId(mContext)
//                    val uuid = SignMd5.getSignMd5Str(mContext)
                    LogUtil.e("uuid=$uuid")

//                    val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags("en-US")
//                    AppCompatDelegate.setApplicationLocales(appLocale)
                }
                1 -> mContext.onStart<SSDemoActivity>(mContext)
                2 ->//测试版本更新
                    (mContext as MainActivity).mDownLoadManage?.showUpdateVersionDialog(
                        "https://dx14.198449.com/xapkanzhuangqi2020.apk",
                        "很爱很爱你",
                        false
                    )
                3 -> {
                    val notifyEntity = NotifyEntity()
                    notifyEntity.title = "测试标题啊"
                    notifyEntity.type = 3
                    NotificationMr.showNotification(mContext, notifyEntity)
                }
                4 -> if (!isLogin) {
                    vm.login("chensj1992", "csj945")
                } else {
                    vm.logout()
                }
                5 -> vm.collect(1165)
            }

        }
        adapter.itemLongClick { _, pos ->
            ToastUtil.showToast("itemLongClick")
            LogUtil.e(list[pos].projectLink)
        }
        v.mRecyclerView.layoutManager = LinearLayoutManager(mContext)
        v.mRecyclerView.adapter = adapter

        v.refreshLayout.setOnRefreshListener {//下拉刷新
            page = 0
            loadData()
        }
        v.refreshLayout.setEnableLoadMore(false) //是否启用上拉加载功能 默认不启用 根据list.size判断
        v.refreshLayout.setOnLoadMoreListener {//上拉加载
            if (adapter.itemCount >= total) {
                v.refreshLayout.finishLoadMoreWithNoMoreData()
            } else {
                page++
                loadData()
            }
        }
    }

    private var time1: Long = 0
    private var count: Int = 0
    private fun loadData() {
        time1 = System.currentTimeMillis()
        vm.getArticleList(page, page == 0)
//        vm.getArticleList(page, page == 0)
//        vm.getArticleList(page, page == 0)
//        LogUtil.e("耗时-》" + (System.currentTimeMillis() - time1))

//        thread {
//            var connection: HttpURLConnection? = null
//            try {
//                val response = StringBuilder()
//                val url = URL("https://www.bing.com")
//                connection = url.openConnection() as HttpURLConnection
//                val input = connection.inputStream
//                val reader = BufferedReader(InputStreamReader(input))
//                reader.use {
//                    reader.forEachLine {
//                        response.append(it)
//                    }
//                }
//                LogUtil.d("TAG", response.toString())
//            } catch (e: Exception) {
//                e.printStackTrace()
//            } finally {
//                connection?.disconnect()
//            }
//        }
    }

    override fun initVM() {
        vm.articlesData.observe(this, Observer {
            count += 1
//            LogUtil.e("耗时$count-》" + (System.currentTimeMillis() - time1))
            if (count == 3) {
                LogUtil.e("多个接口请求结束耗时$count-》" + (System.currentTimeMillis() - time1))
            }
//           total = it.total
            if (it.data != null) {
                canLoad = (it.data.datas?.size ?: 0) > 0
                if (page == 0) {
                    adapter.replaceData(it.data.datas)
                    v.refreshLayout.setEnableLoadMore(canLoad) //数据为空 屏蔽加载更多
                    v.refreshLayout.finishRefresh()
                } else {
                    if (canLoad) {
                        adapter.addData(it.data.datas)
                        v.refreshLayout.finishLoadMore()
                    } else {
                        v.refreshLayout.finishLoadMoreWithNoMoreData()
                    }
                }
            } else {
                canLoad = false
                if (page == 0) {
                    v.refreshLayout.setEnableLoadMore(canLoad) //数据为空 屏蔽加载更多
                    v.refreshLayout.finishRefresh()
                } else {
                    v.refreshLayout.finishLoadMoreWithNoMoreData()
                }
            }
        })

        vm.errorData.observe(this, Observer {
            if (vm.errorData.value!!.index == 1) {
                if (page == 0) {
                    v.refreshLayout.finishRefresh(false)
                } else {
                    v.refreshLayout.finishLoadMore(false)
                }
            } else {
                ToastUtil.showToast(vm.errorData.value!!.errMsg)
            }
        })

        vm.successData.observe(this, Observer {
            when (vm.successData.value) {
                2 -> {
                    ToastUtil.showToast("登录成功")
                    isLogin = true
                }
                3 -> ToastUtil.showToast("收藏成功")
                4 -> {
                    ToastUtil.showToast("退出登录成功")
                    isLogin = false
                }
            }
        })
    }

    override fun lazyLoadData() {
//        loadData()
    }

}